package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.qk.management.anno.Cacheable;
import com.qk.management.constant.CacheKeyConstants;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.ClueMapper;
import com.qk.management.service.PortalOverViewService;
import com.qk.vo.business.BusinessOverViewVo;
import com.qk.vo.clue.ClueOverViewVo;
import com.qk.vo.portal.PortalOverviewVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class PortalOverViewServiceImpl implements PortalOverViewService {
    @Autowired
    private ClueMapper clueMapper;
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    public StringRedisTemplate redisClient;



    @Override
    public PortalOverviewVO reportOverviewWithCache() {
        String rediskey = CacheKeyConstants.CAHE_PORTAL_KEY_PREFIX + "reportOverview";
        String jsonStr = null;
        try {
            jsonStr = redisClient.opsForValue().get(rediskey);
            if (ObjectUtil.isNotEmpty(jsonStr)) {
                //jsonStr to PortalOverviewVO
                PortalOverviewVO vo = JSONUtil.toBean(jsonStr, PortalOverviewVO.class);
                return vo;
            }
        } catch (Exception e) {
            log.error("查询缓存异常", e.getMessage());
        }
        ClueOverViewVo clueOverViewVo = clueMapper.clueOverview();
        BusinessOverViewVo businessOverViewVo = businessMapper.businessOverview();
        PortalOverviewVO portalOverviewVO = BeanUtil.copyProperties(clueOverViewVo, PortalOverviewVO.class);
        BeanUtil.copyProperties(businessOverViewVo, portalOverviewVO);
        try {
            String json = JSONUtil.toJsonStr(portalOverviewVO);
            redisClient.opsForValue().set(rediskey, json);
        }catch (Exception e) {
            log.error("添加缓存异常", e);
        }
        return portalOverviewVO;
    }

    @Cacheable(
            redisKeyPrefix = CacheKeyConstants.CAHE_PORTAL_KEY_PREFIX,
            redisKeyExpireTime = 24*60L,
            redisKeyExpireTimeUnit = TimeUnit.MINUTES
    )
    @Override
    public PortalOverviewVO reportOverview() {
        ClueOverViewVo clueOverViewVo = clueMapper.clueOverview();
        BusinessOverViewVo businessOverViewVo = businessMapper.businessOverview();
        PortalOverviewVO portalOverviewVO = BeanUtil.copyProperties(clueOverViewVo, PortalOverviewVO.class);
        BeanUtil.copyProperties(businessOverViewVo, portalOverviewVO);
        return portalOverviewVO;
    }
}
